<?php
/**
 * Created by PhpStorm.
 * User: xujm
 * Date: 2016/8/9
 * Time: 18:53
 */

use Phalcon\Mvc\Controller;

class ArticleController extends Controller {

    /**
     * 列表页面
     */
    public function indexAction()
    {
        $this->view->posts = Article::find();
    }


    /**
     * 增加的页面
     */
    public function addAction() {}

    /**
     * 增加的逻辑操作
     */
    public function doAddAction()
    {
        $article = new Article();

        /**
         * 保存文章数据
         */

        $article->createtime = time();
        $article->updatetime = time();

        $success = $article->save(
            $this->request->getPost(),
            array('title', 'keywords','desc','hits','isshow','smeta','author','appid','url','content')
        );
        if ($success) {
            $this->view->pick("article/index");
        } else {
            echo "保存失败 ";
            foreach ($article->getMessages() as $message) {
                echo $message->getMessage(), "<br/>";
            }

            $this->view->pick("article/add");
        }


    }
    /**
     * 修改文章页面
     */
    public function editAction($id)
    {

        $id = intval($id);
        $art = Article::findFirst(
            array(
                'id' => $id
            )
        );
        $this->view->post = $art;

    }

    /**
     * 修改文章逻辑
     */
    public function doEditAction()

    {

        $data = $this->request->getPost();
        $id = $data['id'];


        $art = Article::findFirst('id='.$id);
        $art->setAppid($data['appid']);
        $art->setAuthor($data['author']);
        $art->setUpdatetime(time());
        $art->setContent($data['content']);
        $art->setDesc($data['desc']);
        $art->setHits($data['hits']);
        $art->setKeywords($data['keywords']);
        $art->setIsshow($data['isshow']);
        $art->setSmeta($data['smeta']);
        $art->setTitle($data['title']);
        $art->setUrl($data['url']);

        $res = $art->update();


        if ($res) {
            $this->response->redirect( '/article/index' );
        } else {
            echo "保存失败 ";
            foreach ($art->getMessages() as $message) {
                echo $message->getMessage(), "<br/>";
            }

            $this->response->redirect( '/article/index' );
        }

    }
}